<template>
  <el-row class="mt-8px" :gutter="8" justify="space-between">
    <el-col :xl="16" :lg="16" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card>
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.recentVisit') }}</span>
            <el-link type="primary" :underline="false" @click="table = true" v-if="visit.length">{{
              t('action.more')
            }}</el-link>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row v-if="visit.length">
            <el-col v-for="(item, index) in visit" :key="`card-${index}`" :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
              <el-card shadow="hover" class="mr-5px mt-5px cursor-pointer" style="min-height: 88px;"
                @click="go(item.moduleRouter)">
                <div class="flex items-center justify-between">
                  <span class="text-16px">{{ item.moduleName }}</span>
                  <span class="text-12px">{{ formatTime(item.createTime, 'yyyy-MM-dd') }}</span>
                </div>
                <div class="mt-12px flex justify-between text-12px text-gray-400"
                  v-if="item.moduleRouter.indexOf('order') == -1">
                  <span>项目名称：{{ item.projectName }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
          <el-empty description="暂无数据" :image-size="100" v-else />
        </el-skeleton>
      </el-card>
      <el-card class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.productEntry') }}</span>
            <!-- <el-link type="primary" :underline="false">{{ t('action.more') }}</el-link> -->
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <el-row>
            <el-col v-for="(item, index) in products" :key="`card-${index}`" :xl="8" :lg="8" :md="8" :sm="24" :xs="24">
              <el-card shadow="hover" class="mr-5px mt-5px cursor-pointer" @click="go(item.path)">
                <div class="flex items-center">
                  <Icon :icon="item.icon" :size="25" class="mr-8px" />
                  <span class="text-16px">{{ item.name }}</span>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-skeleton>
      </el-card>
      <el-card class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.helpDoc') }}</span>
            <!-- <el-link type="primary" :underline="false">{{ t('action.more') }}</el-link> -->
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <template v-if="docs.length">
            <div v-for="(item, index) in docs" :key="`dynamics-${index}`">
              <p class="report-item">
                <Highlight :keys="item.keys.map((v) => t(v))"> {{ item.type }} : </Highlight>
                <el-link type="default" :underline="true" :href="item.url" target="_blank">
                  {{ item.title }}
                </el-link>
              </p>
              <el-divider />
            </div>
          </template>
          <el-empty description="暂无数据" :image-size="100" v-else />
        </el-skeleton>
      </el-card>
    </el-col>
    <el-col :xl="8" :lg="8" :md="24" :sm="24" :xs="24" class="mb-8px">
      <el-card shadow="never">
        <el-skeleton :loading="loading" animated>
          <div class="flex items-center">
            <el-avatar :src="avatar" :size="70" class="mr-16px">
              <!-- <img src="@/assets/imgs/avatar.gif" alt="" /> -->
            </el-avatar>
            <div>
              <div class="text-16px"> 用户昵称：{{ username }} </div>
              <div class="mt-10px text-16px"> 用户ID: {{ id }} </div>
              <!-- <div class="mt-10px text-14px text-gray-500"> 公司: {{ tenantName }} </div> -->
            </div>
          </div>
        </el-skeleton>
      </el-card>
      <el-card class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.myProject') }}</span>
            <el-link type="primary" :underline="false" @click="go('/projectManage')">{{
              t('workplace.projectManage')
            }}</el-link>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <template v-if="projects.length">
            <div v-for="(item, index) in projects" :key="`card-${index}`" :xl="24" :lg="8" :md="8" :sm="24" :xs="24">
              <el-card shadow="hover" class="mr-5px mt-5px" @click="handleProjectClick(item.id)">
                <div class="justify-between flex">
                  <div class="text-14px"><span class="type mb-5px">{{
                    item.type == '1' ? '普通项目' : 'GitLab项目'
                      }}</span>{{ t(item.name) }}</div>
                  <div class="flex items-center">
                    <Icon icon="ep:user" :size="25" class="mr-8px" />
                    <span class="text-12px">{{ item.members }}</span>
                  </div>
                </div>
              </el-card>
            </div>
          </template>
          <el-empty description="暂无数据" :image-size="100" v-else />
        </el-skeleton>
      </el-card>
      <el-card class="mt-8px">
        <template #header>
          <div class="h-3 flex justify-between">
            <span>{{ t('workplace.myReport') }}</span>
            <el-link type="primary" :underline="false" @click="report = true" v-if="reports.length">{{
              t('action.more')
            }}</el-link>
          </div>
        </template>
        <el-skeleton :loading="loading" animated>
          <template v-if="reports.length" >
            <div v-for="(item, index) in reports.slice(reports.length - 3)" :key="`card-${index}`" :xl="24" :lg="8"
              :md="8" :sm="24" :xs="24" @click="handleView(item.url)">
              <p class="report-item">
                <!-- <Highlight> {{ item.url.split('.')[1] }} : </Highlight> -->
                <el-link type="default" :underline="true">
                  {{ item.name }}
                </el-link>
              </p>
              <el-divider />
            </div>
          </template>
          <el-empty description="暂无数据" v-else/>
        </el-skeleton>
      </el-card>
    </el-col>
  </el-row>

  <!-- 最近访问-更多 -->
  <el-drawer v-model="table" title="最近访问" direction="rtl" size="50%">
    <el-button type="primary" plain style="float: right" @click="clearVisit"> 清空 </el-button>
    <el-table :data="allVisit">
      <el-table-column property="moduleName" label="功能名称" width="150" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="go(scope.row.moduleRouter)">{{
            scope.row.moduleName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column property="projectName" label="项目名称" align="center" />
      <el-table-column property="createTime" label="访问时间" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>

  <!-- 我的报告 -更多 -->
  <el-drawer v-model="report" title="我的报告" direction="rtl" size="50%">
    <el-table :data="reports">
      <el-table-column property="name" label="文件名称" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleView(scope.row.url)">{{
            scope.row.name
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column property="createTime" label="创建时间" align="center">
        <template #default="scope">
          {{ formatTime(scope.row.createTime, 'yyyy-MM-dd HH:mm:ss') }}
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>

  <ViewPdf ref="viewPdf" />
  <ViewFile ref="viewFile" />

</template>
<script lang="ts" setup>
defineOptions({ name: 'Home' })
import * as ViewApi from '@/api/view'
import { formatTime } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { useAppStore } from '@/store/modules/app'
import type { Project, Notice, Product, Visit } from './types'
// import * as authUtil from '@/utils/auth'
import { useTagsViewStore } from '@/store/modules/tagsView'
import ViewPdf from '../expertTestService/commitTestRecord/viewPdf.vue'
import ViewFile from '../order/myOrder/viewFile.vue';
const tagsViewStore = useTagsViewStore()
const message = useMessage() // 消息弹窗
const { push } = useRouter()
const { t } = useI18n()
const userStore = useUserStore()
const appStore = useAppStore()
const loading = ref(true)
const avatar = userStore.getUser.avatar
const username = userStore.getUser.nickname
const id = userStore.getUser.id
// const tenantName = authUtil.getLoginForm()?.tenantName || '中科数测'
// 获取最近访问
const table = ref(false)
const report = ref(false)
let visit = ref<Visit[]>([]) // 展示的
let allVisit = ref<Visit[]>([]) //所有的
const viewPdf = ref()
const viewFile = ref()
const getVisit = async () => {
  let res = await ViewApi.getRecentVisit()
  visit.value = res.slice(0, 3)
  allVisit.value = res.slice(0, 10).map(item => {
    if (item.moduleRouter.indexOf('order') != -1) {
      return {
        ...item,
        projectName: '--'
      }
    } else {
      return item
    }
  })
}

// 清空最近访问
const clearVisit = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm('确定清空最近访问所有数据？')
    // 发起删除
    await ViewApi.clearRecentVisit()
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getVisit()
  } catch { }
}

// 获取我的项目
let projects = reactive<Project[]>([])
const getProject = async () => {
  let res = await ViewApi.getMyProject()
  appStore.setAllProject(res)
  let temp = res.length > 3 ? res.reverse().splice(0, 3) : res
  projects = Object.assign(projects, temp)
}
// 我的项目点击
const handleProjectClick = (id) => {
  appStore.setSelectProject(id)
  // push('/view')
}
// 获取帮助文档
let docs = reactive<Notice[]>([])
const getDocs = async () => {
  const data = [
    {
      title: '测试云平台用户手册',
      type: 'doc',
      keys: ['doc'],
      url: 'https://www.yuque.com/zhaozhe-igbt8/uead03/gc95rrgu1fdbuhgy',
      date: new Date()
    }
  ]
  docs = Object.assign(docs, data)
}

// 获取产品入口
let products = reactive<Product[]>([])

const getProducts = async () => {
  const data = [
    {
      name: '持续集成',
      icon: 'ep:grid',
      path: '/CI'
    },
    {
      name: '需求管理',
      icon: 'ep:aim',
      path: '/test/demandManage'
    },
    {
      name: '提测管理',
      icon: 'ep:checked',
      path: '/test/testingManage'
    },
    {
      name: '用例管理',
      icon: 'ep:odometer',
      path: '/test/useCase'
    },
    {
      name: '测试执行',
      icon: 'ep:credit-card',
      path: '/test/testPlan'
    },
    {
      name: '缺陷管理',
      icon: 'ep:collection-tag',
      path: '/test/defectManage'
    },
    {
      name: '接口调试',
      icon: 'ep:set-up',
      path: '/apiManage/debug'
    },
    {
      name: '自动化测试',
      icon: 'fa:android',
      path: '/apiManage/autoTest'
    }
  ]
  products = Object.assign(products, data)
}

// 获取报告列表
let reports = reactive([] as any)

const getReport = async () => {
  let files = [] as any
  let res = await ViewApi.getUserAllReports({ userId: id })
  res && res.forEach(item => {
    if (item.testReportFile) {
      const fileTemp = JSON.parse(item.testReportFile)
      const fileTemp1 = fileTemp && fileTemp.map(k => {
        return {
          ...k,
          createTime: item.createTime
        }
      })
      files.push(...fileTemp1)
    }
  })
  reports = Object.assign(reports, files)
}

const getAllApi = async () => {
  userStore.resetSetUser()
  await Promise.all([getVisit(), getProject(), getDocs(), getReport(), getProducts()])
  loading.value = false
}

const go = (path) => {
  tagsViewStore.delAllViews()
  push(path)
}
const handleView = (url) => {
  viewFile.value.open(url)
}
getAllApi()
</script>
<style scoped lang="scss">
.type {
  display: block;
  font-size: 12px;
  color: rgb(64, 158, 255);
}

.report-item {
  display: flex;
  margin: 0;
}
</style>
